<!--
  * 实训室管理系统
  *
  * @Author:    王俊权
  * @Date:      2024-11-06 10:32:24
  * @Copyright  🐂🐎bloc
-->
<template>
  <a-modal
      :title="form.id ? '编辑' : '添加'"
      :width="300"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }" >
        <a-form-item label="用户名，必须唯一"  name="username">
          <a-input style="width: 100%" v-model:value="form.username" placeholder="用户名，必须唯一" />
        </a-form-item>
        <a-form-item label="用户密码"  name="password">
          <a-input style="width: 100%" v-model:value="form.password" placeholder="用户密码" />
        </a-form-item>
        <a-form-item label="用户角色"  name="roleName">
		    <a-select v-model:value="form.roleName"   style="width: 100%"    		@change="handleChange" >
	        <a-select-option v-for="item in options" :value="item.value" :key="item.value">
			        {{ item.title }}
          </a-select-option>
        </a-select>
        </a-form-item>
        <a-form-item label="所属部门（对于教师和学生可能是所在系部等，管理员可能为空）"  name="department">
          <a-input style="width: 100%" v-model:value="form.department" placeholder="所属部门（对于教师和学生可能是所在系部等，管理员可能为空）" />
        </a-form-item>
        <a-form-item label="用户邮箱"  name="email">
          <a-input style="width: 100%" v-model:value="form.email" placeholder="用户邮箱" />
        </a-form-item>
        <a-form-item label="用户电话"  name="phone">
          <a-input style="width: 100%" v-model:value="form.phone" placeholder="用户电话" />
        </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick,  defineExpose,watch,onMounted,onUnmounted} from 'vue';
  import _ from 'lodash';
  import { message} from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { usersApi } from '/@/api/business/users/users-api';
  import { smartSentry } from '/@/lib/smart-sentry';
import {roleApi} from '/@/api/system/role-api';

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);





  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    if (form.department && form.department.length > 0) {
      form.department = form.department.map((e) =>e.valueCode );
    }
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

onUnmounted(()=>{
    Object.assign(form, formDefault);
})

//下拉选项
const options = ref([])
const selectV =ref({})




async function getAllRole(){
	let res =  await roleApi.queryAll()
	let option = res.data.map((t)=>{return {value:t.roleId,title:t.roleName}})
	return option
}
 const handleChange = (value) => {
     form.roleId = value

 };



onMounted(() => {
  getAllRole().then((data) => {
    options.value = data;
  });
})



  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
	id:undefined,
      username: undefined, //用户名，必须唯一
      password: undefined, //用户密码
      roleName: undefined, //用户角色，包括管理员、教师、学生
	roleId:undefined,
      department: undefined, //所属部门（对于教师和学生可能是所在系部等，管理员可能为空）
      email: undefined, //用户邮箱
      phone: undefined, //用户电话
  };

  let form = reactive({ ...formDefault });

  const rules = {
      username: [{ required: true, message: '用户名，必须唯一 必填' }],
      password: [{ required: true, message: '用户密码 必填' }],
      roleName: [{ required: true, message: '用户角色，包括管理员、教师、学生 必填' }],
      department: [{ required: true, message: '所属部门（对于教师和学生可能是所在系部等，管理员可能为空） 必填' }],
      email: [{ required: true, message: '用户邮箱 必填' }],
      phone: [{ required: true, message: '用户电话 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (form.id) {
        await usersApi.update(form);
      } else {
        await usersApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,
  });
</script>
